package namespace

import (
	"context"
	"encoding/base64"
	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"krm_backend/config"
	"krm_backend/controllers"
	"krm_backend/utils/logs"
)

func Create_old(r *gin.Context) {
	logs.Debug(nil, "添加namespace")
	basicInfo := controllers.BasicInfo{}
	returnData := config.NewReturnData()
	if err := r.ShouldBindJSON(&basicInfo); err != nil {
		msg := "请求出错: " + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
	}
	// 获取kubeconfig
	kubeconfg := config.ClusterKubeconfig[basicInfo.ClusterId]
	kubeconfigBytes, err := base64.StdEncoding.DecodeString(kubeconfg)
	if err != nil {
		logs.Error(nil, "解码base64失败")
		returnData.Status = 400
		returnData.Message = "解码base64失败"
		r.JSON(200, returnData)
		return
	}

	restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfigBytes)
	if err != nil {
		msg := "解析kubeconfig错误" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}

	// 创建客户端工具
	clientset, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		msg := "创建clientset失败" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	var namespace corev1.Namespace
	namespace.Name = basicInfo.Name

	_, err = clientset.CoreV1().Namespaces().Create(context.TODO(), &namespace, metav1.CreateOptions{})
	if err != nil {
		msg := "创建namespace失败" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
	} else {
		returnData.Status = 200
		returnData.Message = "创建成功"
	}
	r.JSON(200, returnData)
}

func Create(r *gin.Context) {
	logs.Debug(nil, "添加namespace")
	clientset, basicInfo, err := controllers.BasicInit(r, nil)
	returnData := config.NewReturnData()
	if err != nil {
		// 不管什么问题返回给前端
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(200, returnData)
		return
	}
	var namespace corev1.Namespace
	namespace.Name = basicInfo.Name

	_, err = clientset.CoreV1().Namespaces().Create(context.TODO(), &namespace, metav1.CreateOptions{})
	if err != nil {
		msg := "创建namespace失败" + err.Error()
		returnData.Message = msg
	} else {
		returnData.Status = 200
		returnData.Message = "创建成功"
	}
	r.JSON(200, returnData)
}
